﻿@using System.Web.Script.Serialization
@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<div>
    <label>Attribute:</label>
    <select data-bind="options: AvailableProductAttributes, optionsText: 'Name', value: SelectedProductAttribute"></select>
</div>
<div>
    <label>Control Type:</label>
    <select data-bind="options: AvailableAttributeControlTypes, optionsText: 'ControlTypeName', value: SelectedAttributeType"></select>
    
</div>

<div>
 <input type="button" value="Create" data-bind="click:SaveProductVarianAttribute"/>
</div>
@{
    
    var model = ViewBag.Model;
    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}

@section scripts
{
    <script>
        var init = @jsonStr;

        
        function AttributeControlType(controlTypeName, controlTypeValue) {
            this.ControlTypeName = ko.observable(controlTypeName);
            this.ControlTypeValue= ko.observable(controlTypeValue);
        }

        function ProductAttribute(id, name) {

            this.Id = ko.observable(id);
            this.Name= ko.observable(name);
        }
        
        function ProductVariantAttributeModel() {

            var self = this;
            self.PvId = ko.observable(init.PvId);

            var cts =  $.map(init.AvailableAttributeControlTypes, function (a) {
                return new AttributeControlType(a.ControlTypeName, a.ControlTypeValue);
            });

            self.AvailableAttributeControlTypes = ko.observableArray(cts);

            self.SelectedAttributeType = ko.observable();


            var apa= $.map(init.AvailableProductAttributes, function (a) {
                return new ProductAttribute(a.Id, a.Name);
            });

            self.AvailableProductAttributes = ko.observableArray(apa);

            self.SelectedProductAttribute= ko.observable();
            
            self.SaveProductVarianAttribute= function() {
                $.ajax({
                    url: "/api/ProductVariantAttributeApi/InsertProductVariantAttribute",
                    type: 'post',
                    data: ko.toJSON(self),
                    contentType: 'application/json',
                    success: function (result) {

                        if (result.Status == "0") {
                            alert("保存成功");
                            location.href = '/ProductVariantAttributeApi/Edit?productVariantId=' + self.PvId();
                        }
                        else {
                            alert("保存失败：" + result.Msg);
                        }
                    }
                });
            };
        }

        var vm = new ProductVariantAttributeModel();
        ko.applyBindings(vm);
    </script>


}

